using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using Yoozoo.Gameplay;

// Use physics raycast hit from mouse click to set agent destination
[RequireComponent(typeof(NavMeshAgent))]
public class ClickToMove : MonoBehaviour
{
    NavMeshAgent m_Agent;
    RaycastHit m_HitInfo = new RaycastHit();
    private Camera mainCamera;
    List<Vector3> pathList = new List<Vector3>();
    private int nextIndex = 0;
    private float startTime;
    private float speed = 1;
    private float nextPointTime;
    private float pointStartTime;

    void Start()
    {
        m_Agent = GetComponent<NavMeshAgent>();
        //m_Agent.updatePosition = false;
        //m_Agent.updateRotation = false;
        pathList.Clear();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0) && !Input.GetKey(KeyCode.LeftShift))
        {
            //var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //if (Physics.Raycast(ray.origin, ray.direction, out m_HitInfo)){
                //Debug.Log(m_HitInfo.point);
                //m_Agent.destination = m_HitInfo.point;
            //}
            Vector3 position = GetGroundPositionByTouchPosition(Input.mousePosition);
            m_Agent.SetDestination(position);
            pathList.Clear();
            nextIndex = 0;
            for (int i = 0; i < m_Agent.path.corners.Length; i++)
            {
                pathList.Add( m_Agent.path.corners[i]);
            }
            ToNextPoint();
        }

        if (pathList.Count > nextIndex && nextIndex > 0)
        {
            Vector3 targetPosition = pathList[nextIndex];
            Vector3 lastPosition = pathList[nextIndex - 1];
            float percent = (TimeUtils.GetClientTickTime() - pointStartTime) / nextPointTime;
            if (percent < 1)
            {
                transform.position = lastPosition + (targetPosition - lastPosition) * percent + new Vector3(0,1,0);
            }
            else
            {
                ToNextPoint();
            }
        }
    }
    
    private void ToNextPoint()
    {
        if (nextIndex < pathList.Count - 1)
        {
            nextIndex++;
        }
        else
        {
            pathList.Clear();
            return;
        }
        Vector3 targetPosition = pathList[nextIndex];
        Vector3 currentPosition = transform.position;
        pointStartTime = TimeUtils.GetClientTickTime();
        nextPointTime = Vector3.Distance(targetPosition, currentPosition) / speed;
    }
    
    private Vector3 GetGroundPositionByTouchPosition(Vector3 touchPosition)
    {
        if (mainCamera == null)
        {
            mainCamera = WorldCameraManager.mainCamera;
        }
        Ray ray = mainCamera.ScreenPointToRay(touchPosition);
        float p = ray.origin.y / ray.direction.y;
        return ray.origin - ray.direction * p;
    }
}